package com.thekernel.youdaoyun.controller;

import com.alibaba.fastjson.JSONObject;
import com.thekernel.youdaoyun.annotation.Log;
import com.thekernel.youdaoyun.util.PasswordUtils;
import com.thekernel.youdaoyun.util.ResponseUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

/**
 * @Author TheKernel
 * @Date 2019/9/24 5:19 下午
 * @Version 1.0
 * @Description 用于发送验证码等信息
 */
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private JavaMailSender jms;

    /**
     * 邮件发送者邮箱
     */
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 发送验证邮件
     *
     * @param data 接收者
     * @return 发送成功 / 报错信息
     */
//    @Log("send_email")
    @ApiOperation(value = "发送验证码", notes = "根据用户邮箱发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "toEmail", value = "用户邮箱", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("sendVerifyEmail")
    public String sendVerificationCode(@RequestBody JSONObject data) throws MessagingException {
        MimeMessage message;
        message = jms.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo((String) data.get("toEmail"));
        helper.setSubject("云战役签到成功");
        // 处理邮件模板
        Context context = new Context();
        String code = PasswordUtils.generateVerificationCode();
//        context.setVariable("code", code);
        Date date = new Date();
        context.setVariable("date", String.format("签到日期为：%tY年%tm月%td日", date, date, date));
        String template = templateEngine.process("emailTemplate", context);
        helper.setText(template, true);
        jms.send(message);
        HttpSession session = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest()
                .getSession();
        session.setAttribute("verify_code", code);
        return ResponseUtils.response(ResponseUtils.SUCCESS, "send verify code Success !!!", null);
    }

    /**
     * 验证邮件验证码
     *
     * @param data 用户输入的验证码
     * @return 验证正确 / 错误
     */
//    @Log("verify_email")
    @ApiOperation(value = "验证验证码", notes = "根据用户输入的验证码进行验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("verifyEmail")
    public String verificationCode(@RequestBody JSONObject data) throws MessagingException {
        HttpSession session = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest()
                .getSession();
        String realCode = (String) session.getAttribute("verify_code");
        String code = (String) data.get("code");

        if (code.equals(realCode)) {
            return ResponseUtils.response(ResponseUtils.SUCCESS, "verify code Success !!!", null);
        } else {
            return ResponseUtils.response(ResponseUtils.FAILED, "verify code Failed !!!", null);
        }
    }
}
